package com.zzyl.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.dto.ReservationDto;
import com.zzyl.entity.Reservation;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.CustomerReservationMapper;
import com.zzyl.service.CustomerReservationService;
import com.zzyl.utils.UserThreadLocal;
import com.zzyl.vo.ReservationVo;
import com.zzyl.vo.TimeCountVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.time.*;
import java.util.List;
import java.util.Map;

@Service
public class CustomerReservationServiceImpl implements CustomerReservationService {
    @Autowired
    private CustomerReservationMapper customerReservationMapper;

    @Override
    public Integer cancelQuantity() {
        //拿到当前查询人的id
        Long id = UserThreadLocal.get();
       Integer quantity = customerReservationMapper.cancelQuantity(id);
       return quantity;
    }

    @Override
    public List<TimeCountVo> countByTime(Long time) {
        //将时间戳转成LocalDateTime,起始时间和结束时间
        LocalDateTime time0 = LocalDateTime.ofInstant(Instant.ofEpochMilli(time), ZoneId.systemDefault());
        LocalDate localDate = time0.toLocalDate();
        LocalDateTime start = localDate.atStartOfDay();
        LocalDateTime end = localDate.atTime(LocalTime.MAX);
        //查到的次数是各个时间被预约的次数, 需要算出剩余次数
        List<TimeCountVo>lists=customerReservationMapper.countByTime(start,end);
        lists.forEach(o->{
            o.setCount(6-o.getCount());
        });
        return lists;
    }

    @Override
    public void addReservation( ReservationDto reservationDto) {
        Integer count = cancelQuantity();
        if(count>3){
            throw new BaseException(BasicEnum.RESERVATION_CANCEL_COUNT_UPPER_LIMIT);
        }
        Reservation reservation = new Reservation();
        BeanUtils.copyProperties(reservationDto,reservation);
        customerReservationMapper.insert(reservation);
    }

    @Override
    public PageResponse getPage(Integer pageNum, Integer pageSize, Integer status) {
        PageHelper.startPage(pageNum, pageSize);
        Page<ReservationVo>page0= customerReservationMapper.getPage(status);
        return PageResponse.of(page0, ReservationVo.class);
    }

    @Override
    public void cancel(Long id) {
       Reservation reservation= customerReservationMapper.selectById(id);
       reservation.setStatus(2);
       customerReservationMapper.updateById(reservation);
    }
}
